package com.cscec5b.inspection.repository;

import com.cscec5b.inspection.entity.DetailInspectionOriginal;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

public interface DetailInspectionOriginalRepository extends JpaRepository<DetailInspectionOriginal, Long> {

    // 接收到任务同步命令时同步任务记录 UPSERT：以 (task_id, task_item_id) 的唯一键为冲突条件
    @Modifying
    @Transactional
    @Query(value = """
        INSERT INTO detail_inspection_original
          (task_id, task_item_id, fail_resample, inspect_item_id, inspect_item, members, data_type)
        VALUES
          (:taskId, :taskItemId, :failResample, :inspectItemId, :inspectItem, :membersJson, :dataType)
        ON DUPLICATE KEY UPDATE
          fail_resample   = VALUES(fail_resample),
          inspect_item_id = VALUES(inspect_item_id),
          inspect_item    = VALUES(inspect_item),
          members         = VALUES(members),
          data_type       = VALUES(data_type)
        """, nativeQuery = true)
    int upsert(@Param("taskId") Long taskId,
               @Param("taskItemId") Integer taskItemId,
               @Param("failResample") String failResample,
               @Param("inspectItemId") Integer inspectItemId,
               @Param("inspectItem") String inspectItem,
               @Param("membersJson") String membersJson,
               @Param("dataType") Integer dataType);

    @Query(value = "select * from detail_inspection_original where task_id = :taskId",
            nativeQuery = true)
    List<DetailInspectionOriginal> findAllByTaskId(@Param("taskId") Long taskId);
}
